<template>
  <div class="login">
    <div class="box">
      <el-form
        size="small"
        :model="formData"
        status-icon
        :rules="rules"
        ref="form"
        label-width="50px">
        <el-form-item label="账号" prop="loginId">
          <el-input v-model="formData.loginId"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="loginPwd">
          <el-input
            type="password"
            v-model="formData.loginPwd"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm()"
            >登录</el-button>
          <el-button @click="resetForm()">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {$login} from '../api/adminAPI'
export default {
  data() {
    // 验证账号
    var checkLoginId = (rule, value, callback) => {
      if (!value) {
        callback(new Error("账号不能为空"));
      }else{
        callback();
      }
    };
    // 验证密码
    var checkLoginPwd = (rule, value, callback) => {
      if (!value) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    };
    return {
      //表单数据
      formData: {
        loginId: "",
        loginPwd: "",
      },
      //表单验证
      rules: {
        loginId: [{ validator: checkLoginId, trigger: "blur" }],
        loginPwd: [{ validator: checkLoginPwd, trigger: "blur" }],
      },
    };
  },
  methods: {
    //表单提交方法
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let ret = await $login(this.formData)
          if(ret.code==0){
            //消息框
            this.$message({
              showClose: true, //是否带关闭按钮
              type:'success',  //消息框类型
              message:ret.message   //消息框内容
            })
            // 将登录用户信息保存到浏览器缓存中
            sessionStorage.setItem('user',JSON.stringify(ret.data))
            // 登录成功以后，跳转到首页
            this.$router.push('/index')
          }else{
            this.$message({
              showClose: true,
              type:'error',
              message:ret.message
            })
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //表单重置方法
    resetForm() {
      this.$refs.form.resetFields();
    },
  },
  mounted(){
    if(sessionStorage.getItem('user')){
      this.$router.push('/index')
    }
  }
};
</script>

<style lang="scss" scoped>
.login {
  width: 100vw;
  height: 100vh;
  background-color: #369;
  display: flex;
  justify-content: center;
  align-items: center;
  .box {
    width: 450px;
    padding: 20px;
    border: 1px solid white;
    border-radius: 8px;
    ::v-deep .el-form-item__label{
      color: white;
    }
  }
}
</style>
